<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
	<meta name="author" content="Corey Birnbaum" />
	<title>Grid</title>

	<link href="css/normalize.css" rel="stylesheet" type="text/css"/>
	<style>
		body {
			overflow: hidden;
		}
		#view {
			position: absolute;
			top: 0;
			left: 0;
		}
	</style>
</head>

<body>

	<div id="view"></div>

	<script type="text/javascript" src="../lib/three.min.js"></script>
	<script type="text/javascript" src="../lib/OrbitControls.js"></script>
	<script type="text/javascript" src="../dist/hex-grid.min.js"></script>
	<script type="text/javascript" src="js/Sprite.js"></script>
	<script type="text/javascript">
	window.addEventListener('load', function(evt) {
		// setup the thing
		var scene = new vg.Scene({
			element: document.getElementById('view'),
			cameraPosition: {x:0, y:150, z:150}
		}, true);

		/*var grid = new vg.HexGrid({
			cellSize: 10
		});*/
		var grid = new vg.SqrGrid({
			cellSize: 10 // size of individual cells
		});

		grid.generate({
			size: 10 // size of the board
		});

		var mouse = new vg.MouseCaster(scene.container, scene.camera);
		var selector = new vg.SelectionManager(mouse);
		var board = new vg.Board(grid);

		board.generateTilemap();

		scene.add(board.group);
		scene.focusOn(board.group);

		// populate the board
		var i, sprites = [];
		var spriteConfig = {
			container: board.group,
			url: '../examples/img/water.png',
			scale: 10,
			heightOffset: 6
		};

		for (i = 0; i < 5; i++) {
			sprites[i] = new Sprite(spriteConfig);
			sprites[i].activate(vg.Tools.randomInt(100), vg.Tools.randomInt(grid.extrudeSettings.amount + 15, 40), vg.Tools.randomInt(100));
		}

		// keep track of states
		var currentPiece = 0;
		var movingPiece = null;

		// handle interaction
		selector.onSelect.add(function(obj) {
			if (obj.objectType === vg.TILE) {
				// select the sprite if one was already there
				var e = obj.entity;
				if (e) {
					selector.select(e, false); // don't fire the signal when firing manually or you'll cause a stack overflow with recursion
					movingPiece = e; // new move
				}
				else {
					if (movingPiece) {
						moveEntityToCell(obj);
						return;
					}
					// cycle through the sprites, placing them on the clicked tile
					var p = sprites[currentPiece++];
					if (currentPiece === sprites.length) {
						currentPiece = 0;
					}
					board.setEntityOnTile(p, obj);

				}
			}
			else {
				movingPiece = obj;
			}
		}, this);

		/*selector.onDeselect.add(function(obj) {

		}, this);*/

		function moveEntityToCell(tile) {
			board.setEntityOnTile(movingPiece, tile);
			movingPiece = null;
		}

		// start the thing
		update();
		function update() {
			mouse.update();
			scene.render();
			requestAnimationFrame(update);
		}
	});
	</script>
</body>
</html>
